package com.yanqu.road.server.cmd.house;

import com.yanqu.road.entity.player.UserHouseBar;
import com.yanqu.road.logic.pb.HousePb;
import com.yanqu.road.pb.house.HouseProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.HouseModule;
import com.yanqu.road.server.manger.config.HouseMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.string.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Cmd(code = Protocol.S_HOUSE_BAR_GET_REWARD, desc = "柜台领取奖励")
public class HouseBarGetRewardCmd extends AbstractCommand {

	private int pos;

	Map<String, Property> rewardMap = new ConcurrentHashMap<>();

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		HouseProto.HouseBarGetRewardReqMsg reqMsg = HouseProto.HouseBarGetRewardReqMsg.parseFrom(packet.getBytes());
		pos = reqMsg.getPos();
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		Map<Integer,UserHouseBar> userHouseBarMap = player.getModule(HouseModule.class).getUserHouseBarMap();
		if (pos != 0 && !userHouseBarMap.containsKey(pos)) {
			ret = GameErrorCode.E_HOUSE_BAR_POSITION_ERROR;
			return;
		}

		if(pos != 0){
			UserHouseBar userHouseBar = userHouseBarMap.get(pos);
			if(System.currentTimeMillis() - userHouseBar.getDispatchTime() + userHouseBar.getSurplusTime() < HouseMgr.getHouseProduceTime(player.getUserInfo().getHouseCreditLv()) * 1000){
				ret = GameErrorCode.E_HOUSE_BAR_GET_REWARD_LIMITTIME;
				return;
			}
		}

		rewardMap = player.getModule(HouseModule.class).getBarReward(pos);
		player.getModule(HouseModule.class).syncUserHouseBank();

	}

	@Override
	public void sendData(GamePlayer player) {
		HouseProto.HouseBarGetRewardRespMsg.Builder respMsg = HouseProto.HouseBarGetRewardRespMsg.newBuilder();
		respMsg.setRet(ret);
		for(String posAndPatronsId : rewardMap.keySet()){
			List<Integer> intList = StringUtils.stringToIntegerList(posAndPatronsId,"-");
			respMsg.addRewardList(HousePb.parseHouseBarRewardTempMsg(intList.get(0),intList.get(1),rewardMap.get(posAndPatronsId)));
		}
		player.sendPacket(Protocol.U_HOUSE_BAR_GET_REWARD, respMsg);
	}
}
